#!/bin/bash
CUR_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
BUILD_DIR=/tmp/nfs4
TGZ_NAME=nfs4.tar.gz
DESTDIR=$BUILD_DIR/package
mkdir -p $DESTDIR

rm -rf /var/lib/dpkg/lock-frontend
rm -rf /var/lib/dpkg/lock

apt install -y autoconf automake libtool make fakeroot build-essential debhelper dh-python \
  libevent-dev libsqlite3-dev libdevmapper-dev libkrb5-dev libkeyutils-dev pkg-config \
  libmount-dev libsystemd-dev

# tirpc-dev
cd $BUILD_DIR
git clone git://git.linux-nfs.org/projects/steved/libtirpc.git -b libtirpc-1-3-3
cd libtirpc
chmod +x autogen.sh
sh autogen.sh
./configure
make
make install DESTDIR=$DESTDIR
make install

#rpcbind
cd $BUILD_DIR
#http://git.linux-nfs.org/?p=steved/rpcbind.git;a=summary
git clone git://git.linux-nfs.org/projects/steved/rpcbind.git -b rpcbind-1_2_6
cd rpcbind
sh autogen.sh
./configure
make
make install
make install DESTDIR=$DESTDIR

#nfs-utils
cd $BUILD_DIR
git clone git://git.linux-nfs.org/~steved/nfs-utils.git
cd nfs-utils
git pull
sh autogen.sh
./configure
make
make install DESTDIR=$DESTDIR
make install

# create install.sh
cat > $BUILD_DIR/package/install.sh << EOF
#!/bin/bash
CUR_DIR="\$( cd "\$( dirname "\${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
ROOT=
read_dir() {
  subs=\$(ls \$1)
  for i in \$subs; do
    if [ -f \$1/\$i ]; then
      targetPath=\$ROOT/\$(dirname "\$1/\$i" | sed "s|\$CUR_DIR/||g")
      mkdir -p \$targetPath
      bash -xc "install -c -p -m 0755 \$1/\$i \$targetPath/"
      echo "\$targetPath/\$i" >> \$CUR_DIR/filelist
    elif [ -d \$1/\$i ]; then
      read_dir \$1/\$i
    fi
  done
}

rm -rf \$CUR_DIR/filelist
read_dir \$CUR_DIR
EOF
cat > $BUILD_DIR/package/uninstall.sh << EOF
#!/bin/bash
CUR_DIR="\$( cd "\$( dirname "\${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
set -x
rm -rf \$(cat \$CUR_DIR/filelist | grep -v install)
EOF

cat > $CUR_DIR/make_clean.sh << EOF
#!/bin/bash
CUR_DIR="\$( cd "\$( dirname "\${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
set -x
rm -rf $BUILD_DIR -rf
EOF

chmod +x $BUILD_DIR/package/install.sh
chmod +x $BUILD_DIR/package/uninstall.sh
chmod +x $CUR_DIR/package/clean.sh

cd $BUILD_DIR/
tar zcvf $TGZ_NAME package/
mv $TGZ_NAME $CUR_DIR/
cd $CUR_DIR/
